package com.xzx.protobuf2;

import com.xzx.protobuf.StudentPB;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/11/7 11:19
 */
@Slf4j
public class PBClientHandler extends SimpleChannelInboundHandler<MessagePB.Message> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessagePB.Message msg) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int random = new Random().nextInt(2);
        MessagePB.Message msg;
        if (random == 0) {
            msg = MessagePB.Message.newBuilder().setType(MessagePB.Message.Type.STUDENT)
                    .setStudent(MessagePB.Student.newBuilder().setId(22222).setName("student23").setAge(18).build()).build();
        } else {
            msg = MessagePB.Message.newBuilder().setType(MessagePB.Message.Type.TEACHER)
                    .setTeacher(MessagePB.Teacher.newBuilder().setId(2222).setName("teacher3").setAge(18).build()).build();
        }
        ctx.writeAndFlush(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exceptionCaught", cause);
    }
}
